package com.cooper.service.trade;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.cooper.constants.ResourceConstants;
import com.cooper.core.JsonResult;
import com.cooper.domain.OrderEntry;
import com.cooper.entity.ItemInfo;
import com.cooper.entity.ItemSku;
import com.cooper.entity.OrderAddress;
import com.cooper.entity.OrderInfo;
import com.cooper.entity.OrderItem;
import com.cooper.entity.UserInfo;
import com.cooper.pagination.PageInfo;
import com.cooper.pagination.PageResult;
import com.cooper.service.account.SendAddressService;
import com.cooper.service.item.ItemRepository;
import com.cooper.service.item.ItemSkuService;
import com.cooper.util.BeanUtils;
import com.cooper.util.Controllers;
import com.cooper.util.DateUtils;
import com.cooper.util.StringUtils;
import com.cooper.vo.OrderCreateVo;
import com.cooper.vo.OrderSearchVo;
import com.cooper.vo.SendAddressVo;

@Service
public class OrderService extends OrderRepository{
	
	@Autowired
	private OrderRepository orderRepository;
	
	@Autowired
	private ItemRepository itemRepository;
	
	@Autowired
	private ItemSkuService itemSkuService;
	
	@Autowired
	private SendAddressService sendAddressService;
	
	public JsonResult validateSaveOrderParam(UserInfo userInfo, 
			OrderCreateVo createVo, List<OrderItem> orderItems) throws Exception{
		JsonResult json = new JsonResult();
		if(null == userInfo){
			json.setMessage("PLEASE SIGN IN FIRST! ");
			return json;
		}
		if(CollectionUtils.isEmpty(orderItems)){
			json.setMessage("PLEASE SELECT ITEMS FIRST! ");
			return json;
		}
		
		for(OrderItem orderItem: orderItems){
			Long mealId = orderItem.getMealId();
			Long itemId = orderItem.getItemId();
			int amount = orderItem.getAmount();
			String propKey = orderItem.getPropKey();
			if(null == itemId || 0 == itemId){
				json.setMessage("商品参数中itemId错误");
				return json;
			}
			ItemInfo itemInfo = this.itemRepository.loadById(itemId);
			if(null == itemInfo){
				json.setMessage("商品不存在, id:["+itemId+"]");
				return json;
			}
			if(amount <= 0){
				json.setMessage("数量必须为大于0的正整数");
				return json;
			}
			if(null == mealId || 0 == mealId){
				if(StringUtils.isEmpty(propKey)){
					if(amount > itemInfo.getQuantity()){
						json.setMessage("商品[" + itemInfo.getTitle() + "]库存不足。");
						return json;
					}
				} else {
					ItemSku itemSku = this.itemSkuService.getItemSkuByItemIdAndPropKey(itemId, propKey);
					if(null == itemSku){
						json.setMessage("商品[" + itemInfo.getTitle() + "],propKey:[" + propKey + "]未找到库存信息");
						return json;
					}
					if(amount > itemSku.getQuantity()){
						json.setMessage("商品[" + itemInfo.getTitle() + "],propKey:[" + propKey + "]库存不足。");
						return json;
					}
				}
			} else {
				ItemInfo mealInfo = this.itemRepository.loadById(mealId);
				if(null == mealInfo){
					json.setMessage("套餐不存在, id[" + mealId + "].");
					return json;
				}
				if(amount > mealInfo.getQuantity()){
					json.setMessage("商品[" + mealInfo.getTitle() + "]库存不足。");
					return json;
				}
			}
		}
		json.setSuccess(true);
		return json;
	}
	
	public OrderEntry makeOrderEntry(UserInfo userInfo, SendAddressVo addressVo,
			OrderCreateVo createVo, List<OrderItem> orderItems) throws Exception{
		OrderEntry entry = new OrderEntry();
		String orderNum = DateUtils.formatNow("yyyyMMddHHmmss") + StringUtils.getUUID().substring(0, 6);
		entry.setOrderNum(orderNum);
		
		//收货信息
		OrderAddress orderAddress = new OrderAddress();
		BeanUtils.copyProperties(addressVo, orderAddress);
		Controllers.prepareEntityForDataSaving(orderAddress, userInfo, false);
		BigDecimal totalPrice = new BigDecimal(0);
		
		//订单行
		List<OrderItem> orderItemList = new ArrayList<OrderItem>();
		Long sellerGroupId = 0L;
		for(OrderItem orderItem: orderItems){
			Controllers.prepareEntityForDataSaving(orderItem, userInfo, false);
			Long mealId = orderItem.getMealId();
			Long itemId = orderItem.getItemId();
			String propKey = orderItem.getPropKey();
			
			ItemInfo itemInfo = this.itemRepository.loadById(itemId);
			orderItem.setMainUrl(this.itemRepository.getItemMainUrl(itemId));
			orderItem.setItemTitle(itemInfo.getTitle());
			BigDecimal executePrice = new BigDecimal(itemInfo.getPrice() - itemInfo.getDiscountVolume());
			if(0 == mealId || mealId.equals(itemId)){//单品
				if(StringUtils.isEmpty(propKey)){
					orderItem.setExecutePrice(executePrice);
					orderItem.setFavourPrice(executePrice);
				} else {
					ItemSku itemSku = this.itemSkuService.getItemSkuByItemIdAndPropKey(itemId, propKey);
					orderItem.setPropName(itemSku.getPropsName());
					executePrice = new BigDecimal(itemSku.getPrice());
					orderItem.setExecutePrice(executePrice);
					orderItem.setFavourPrice(executePrice);
				}
			} else {
//				ItemSku itemSku = this.itemInfoService.getMealSkuByItemIdAndPropKey(mealId, itemId, propKey);
//				orderItem.setPropName(itemSku.getPropName());
//				orderItem.setExecutePrice(itemSku.getExecutePrice());
//				orderItem.setFavourPrice(null == itemSku.getFavourPrice()?itemSku.getExecutePrice():itemSku.getFavourPrice());
			}
			totalPrice = totalPrice.add(orderItem.getTotalPrice());
			orderItemList.add(orderItem);
			
			if(0 == sellerGroupId){
				sellerGroupId = itemInfo.getSellerId();
			}
		}
		
		//订单头
		OrderInfo orderInfo = new OrderInfo();
		Controllers.prepareEntityForDataSaving(orderInfo, userInfo, false);
		orderInfo.setUserId(userInfo.getId());
		orderInfo.setGroupId(sellerGroupId);
		orderInfo.setTotalPrice(totalPrice);
		orderInfo.setPayment(totalPrice);
		orderInfo.setBuyerMemo(createVo.getBuyerMemo());
		
		entry.setOrderInfo(orderInfo);
		entry.setOrderItems(orderItemList);
		entry.setOrderAddress(orderAddress);
		entry.setOrderNumber();
		return entry;
	}
	
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	public Long saveOrder(OrderEntry entry, UserInfo userInfo, SendAddressVo addressVo) throws Exception{
		if(0 == addressVo.getId()){
			this.sendAddressService.saveAddressVo(addressVo, userInfo, 
					ResourceConstants.AddressOrigin.RECEIVE_ADDRESS, ResourceConstants.Lang.EN_US);
		}
		return this.orderRepository.addOrder(entry);
	}
	
	public OrderInfo getOrderInfo(String orderNum) throws Exception{
		return this.orderRepository.getOrderInfo(orderNum);
	}
	
	/**
	 * 查询订单，现阶段是买家和卖家共用一个，searchVo中userId不为空则为买家
	 * @param pageInfo
	 * @param searchVo
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public PageResult<OrderEntry> queryForList(OrderSearchVo searchVo, PageInfo pageInfo) throws Exception{
		int rowCount = this.queryOrderInfoCount(searchVo);
		pageInfo.setRowCount(rowCount);
		if(0 == rowCount){
			return new PageResult<OrderEntry>(Collections.EMPTY_LIST, pageInfo);
		}
		
		List<OrderEntry> entryList = new ArrayList<OrderEntry>();
		List<String> orderNumList = this.queryOrderNumList(searchVo, pageInfo);
		if(CollectionUtils.isNotEmpty(orderNumList)){
			for(String orderNum: orderNumList){
				entryList.add(this.getOrderEntry(orderNum));
			}
		}
		return new PageResult<OrderEntry>(entryList, pageInfo);
	}
	
}
